<%@ page language="java" pageEncoding="UTF-8"%>
<%@include file="/views/common/include/taglib.jsp"%>
	<link rel="stylesheet" href="${ctx}/js/lib/ztree/zTreeStyle/zTreeStyle.css" type="text/css">
	<link type="text/css" rel="stylesheet" href="${ctx}/css/dlifestyle/org.css" />
	<script type="text/javascript" src="${ctx}/js/lib/ztree/jquery.ztree.all-3.5.js"></script>
	<script type="text/javascript">
	function setCtx(ctx){
		this.ctx = ctx;
	}
	</script>
	
			<section class="scrollable padder">
              <div style="height:40px;line-height: 40px;">
                    <div class="forword_area"></div>
					<div class="location">当前位置：${sessionScope.currcent_position}</div>

              </div>
              <hr>
		              <section>
		              	
					    <!--begin 搜索栏 -->
			                  <div class="panel" >
				                  <div  style="float:left;height: 28px;">
				                  
							        <!--搜索框-->
						        	<!-- <label>部门名称：</label> -->
						            <input id="search_condition" type="text" placeholder="请输入搜索条件" class="input-sm" />
								   </div> 
						             <div class="form-control">
						            	 <div class="search" onclick="search_ztree('treeDemo', 'search_condition')"><img src="${ctx }/images/table/search_second.png"></div>
						            	 <div class="search" onclick="saveOrUpdateCategory();"><img src="${ctx }/images/table/add_second.png"></div>
						             	 <input type="hidden" id="callbackTrigger" />
									     <div class="delete" id="remove" title="删除" onclick="return false;">
											<img src="${ctx }/images/table/del_second.png">
										</div>
						             </div>
			                </div>
			                <!--end 搜索栏 -->
		              	
		              		<!--生成树  -->
							<div class="content_wrap" style="width:210px;float:left;margin-top: 20px;">
								<div class="modal-header">
									<ul style="min-height: 40px;line-height: 40px;margin-left: 20px;">
									<li style="display:inline-block;list-style:none;">
										<img src="${ctx }/images/system/org_title.png">
									</li>
									<li style="display:inline-block;width: 100px;">
										<h4 class="modal-title" style="text-indent: 0;">商品分类</h4>
									</li>
									</ul>
								</div>
								<div class="zTreeDemoBackground left">
									<ul id="treeDemo" class="ztree"></ul>
								</div>
							</div>
							
							<!--分类详情  -->
							<div id="orgDetail" class="right" style=" margin-left: 280px;  margin-top: 20px;height: 150px;">
									<div class="modal-header">
										<h4 class="modal-title">分类详情</h4>
									<!-- begin table表格 -->
								<table style="width:100%; margin-top:0px;table-layout:fixed" class="table table-striped b-t b-light">
									<tr>
										<td width="10%" style="background-color: #e0eff3;height:40px">分类名称 </td>
										<td width="10%" style="background-color: #e0eff3;height:40px">分类描述</td>
										<td width="10%" style="background-color: #e0eff3;height:40px">分类级别</td>
										<td width="10%" style="background-color: #e0eff3;height:40px">配送</td>
										<td width="10%" style="background-color: #e0eff3;height:40px">平台服务费</td>
										<td width="10%" style="background-color: #e0eff3;height:40px">商家确认</td>
										<td width="10%" style="background-color: #e0eff3;height:40px">操作</td>
									</tr>
									<tr>
										<td><span id="name"></span></td>
										<input id="categoryId" type="hidden" />
										<td  style = "width:10px;text-overflow:ellipsis;white-space:nowrap;overflow:hidden;"><span id="descrip"></span></td>
										<td><span id="level"></span></td>
										<td><span id="isNeedDistribute"></span></td>
										<td><span id="isServicePrice"></span></td>
										<td><span id="isNeedConfrim"></span></td>
										<td>
											<a class="fa fa-check " onclick="editCategory();" >编辑</a>
			                          	</td>
									</tr>
								</table>
									</div>
								
							</div>
							
							<!--分类属性详情  -->
							<!-- <div  class="right" style=" margin-left: 280px;  margin-top: 20px;">
									<div id="categoryAttrDetail"></div>

							</div> -->
		            </section>
			</section>
		<input type="hidden" id="pid"/>
	<%@include file="/views/common/footer.jsp"%>
  	<script type="text/javascript">
  	

		var ctx = '${ctx}';
		
		/* document.getElementById("myFrom").reset(); */
		

		var curMenu = null, zTree_Menu = null;
		var setting = {
			view: {
				showLine: true,
				showIcon: true,
				selectedMulti: false,
				dblClickExpand: false,
				addDiyDom: addDiyDom,
				fontCss: setFontCss_ztree
			},
			edit: {
				enable: true,
				showRemoveBtn: false,
				showRenameBtn: false
				},
			data: {
				keep: {
					parent:true,
					leaf:true
				},
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: "pId",
					rootPid: null 
				}
			},
			callback: {
				/* beforeClick: beforeClick, */
				onClick : onClick,
				onAsyncSuccess: zTreeOnAsyncSuccess,
				beforeDrag: beforeDrag,
				beforeExpand: beforeExpand,
				onExpand: onExpand
				
			}
		};

  		var zNodes;
  		
  		function onClick(event, treeId, treeNode, clickFlag) {  
  			
			var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
			nodes = zTree.getSelectedNodes(),
			treeNode = nodes[0];
			
			loading(treeNode);
			
			zTree.expandNode(treeNode, null, null, null, true);

  		}
  		
  		function loading(treeNode){
 		   $.ajax({
			    async:true,//是否异步
			    cache:false,//是否使用缓存
			    type:'get',//请求方式：post
			    dataType:'json',//数据传输格式：json
			    url:ctx + "/goodsCategory/categoryDetail?id=" + treeNode.id ,//请求的action路径
			    error:function(){
			      //请求失败处理函数
			    	layer.msg('请求失败!', {icon: 5});
			    },
			    success:function(data){
			    	$("#name").text(data.name);
			    	$("#descrip").text(data.descrip);
			    	$("#categoryId").val(data.id);
			    	
			    	if(1 == data.level){
			    		$("#level").text("一级");
			    	}else if(2 == data.level){
			    		$("#level").text("二级");
			    	}
			    	if(1 == data.isNeedDistribute){
			    		$("#isNeedDistribute").text("是");
			    	}else if(0 == data.isNeedDistribute){
			    		$("#isNeedDistribute").text("否");
			    	}
			    	if(1 == data.isServicePrice){
			    		$("#isServicePrice").text("是");
			    	}else if(0 == data.isServicePrice){
			    		$("#isServicePrice").text("否");
			    	}
			    	if(1 == data.isNeedConfrim){
			    		$("#isNeedConfrim").text("是");
			    	}else if(0 == data.isNeedConfrim){
			    		$("#isNeedConfrim").text("否");
			    	}
			    	
			    	if(data.leaf){
			      		$("#categoryAttrDetail").load(getUrl('${ctx}/goodsCategory/categoryAttrList?categoryId=' + treeNode.id));
			    	}else{
			    		$("#categoryAttrDetail").html('');
			    	}
			    	
   		   }
  			});
  		}
  		
 		function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
 			zNodes = JSON.parse(msg);
 			layer.msg(msg, {icon: 5});
 		};
 			
		function addDiyDom(treeId, treeNode) {
			var spaceWidth = 5;
			var switchObj = $("#" + treeNode.tId + "_switch"),
			icoObj = $("#" + treeNode.tId + "_ico");
			switchObj.remove();
			icoObj.before(switchObj);

			if (treeNode.level > 1) {
				var spaceStr = "<span style='display: inline-block;width:" + (spaceWidth * treeNode.level)+ "px'></span>";
				switchObj.before(spaceStr);
			}
		}

		
		var treeNodes;
		 
		function onLoadZTree(){
			   $.ajax({
			    async:true,//是否异步
			    cache:false,//是否使用缓存
			    type:'post',//请求方式：post
			    dataType:'json',//数据传输格式：json
			    url:ctx + "/goodsCategory/categoryTree",//请求的action路径
			    error:function(){
			      //请求失败处理函数
			      layer.msg('请求失败!', {icon: 5});
			    },
			    success:function(data){
			    	if(!data.success){
			    		layer.msg(data.msg, {icon: 5});
			    		return;
			    	}
			      	var t = $("#treeDemo");
					 $.fn.zTree.init(t, setting, eval(data.obj));
					 
					 //初始化树时默认选择第一个节点
						zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
						curMenu = zTree_Menu.getNodes();
					      if (curMenu.length>0){
				            zTree_Menu.selectNode(curMenu[0]);
				            loading(curMenu[0]);
					      }
			    	}
			  });
		}
		
		$(document).ready(function(){
			
			onLoadZTree();
			
			/* $("#orgLevel").hide(); */
		});
			
		
		//==========================搜索树begin===================================//
		
		/**
     * 展开树
     * @param treeId  
     */
    function expand_ztree(treeId){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        treeObj.expandAll(true);
    }
     
    /**
     * 收起树：只展开根节点下的一级节点
     * @param treeId
     */
    function close_ztree(treeId){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        var nodes = treeObj.transformToArray(treeObj.getNodes());
        var nodeLength = nodes.length;
        for (var i = 0; i < nodeLength; i++) {
            if (nodes[i].id == '0') {
                //根节点：展开
                treeObj.expandNode(nodes[i], true, true, false);
            } else {
                //非根节点：收起
                treeObj.expandNode(nodes[i], false, true, false);
            }
        }
    }
     
    /**
     * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
     * @param treeId
     * @param searchConditionId 文本框的id
     */
    function search_ztree(treeId, searchConditionId){
        searchByFlag_ztree(treeId, searchConditionId, "");
    }
     
    /**
     * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
     * @param treeId
     * @param searchConditionId     搜索条件Id
     * @param flag                  需要高亮显示的节点标识
     */
    function searchByFlag_ztree(treeId, searchConditionId, flag){
        //<1>.搜索条件
        var searchCondition = $('#' + searchConditionId).val();
      	//解决ie9以下placeholder与value重复的问题
    	if(searchCondition == $('#' + searchConditionId).attr("placeholder")){
    		searchCondition = "";
    	}
        //<2>.得到模糊匹配搜索条件的节点数组集合
        var highlightNodes = new Array();
        if (searchCondition != "") {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            highlightNodes = treeObj.getNodesByParamFuzzy("name", searchCondition, null);
        }
        //<3>.高亮显示并展示【指定节点s】
        highlightAndExpand_ztree(treeId, highlightNodes, flag);
    }
     
    /**
     * 高亮显示并展示【指定节点s】
     * @param treeId
     * @param highlightNodes 需要高亮显示的节点数组
     * @param flag           需要高亮显示的节点标识
     */
    function highlightAndExpand_ztree(treeId, highlightNodes, flag){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        //<1>. 先把全部节点更新为普通样式
        var treeNodes = treeObj.transformToArray(treeObj.getNodes());
        for (var i = 0; i < treeNodes.length; i++) {
            treeNodes[i].highlight = false;
            treeObj.updateNode(treeNodes[i]);
        }
        //<2>.收起树, 只展开根节点下的一级节点
        close_ztree(treeId);
        //<3>.把指定节点的样式更新为高亮显示，并展开
        if (highlightNodes != null) {
            for (var i = 0; i < highlightNodes.length; i++) {
                if (flag != null && flag != "") {
                    if (highlightNodes[i].flag == flag) {
                        //高亮显示节点，并展开
                        highlightNodes[i].highlight = true;
                        treeObj.updateNode(highlightNodes[i]);
                        //高亮显示节点的父节点的父节点....直到根节点，并展示
                        var parentNode = highlightNodes[i].getParentNode();
                        var parentNodes = getParentNodes_ztree(treeId, parentNode);
                        treeObj.expandNode(parentNodes, true, true, false);
                        treeObj.expandNode(parentNode, true, true, false);
                    }
                } else {
                    //高亮显示节点，并展开
                    highlightNodes[i].highlight = true;
                    treeObj.updateNode(highlightNodes[i]);
                    //高亮显示节点的父节点的父节点....直到根节点，并展示
                    var parentNode = highlightNodes[i].getParentNode();
                    var parentNodes = getParentNodes_ztree(treeId, parentNode);
                    treeObj.expandNode(parentNodes, true, true, false);
                    treeObj.expandNode(parentNode, true, true, false);
                }
            }
        }
    }
     
    /**
     * 递归得到指定节点的父节点的父节点....直到根节点
     */
    function getParentNodes_ztree(treeId, node){
        if (node != null) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            var parentNode = node.getParentNode();
            return getParentNodes_ztree(treeId, parentNode);
        } else {
            return node;
        }
    }
     
    /**
     * 设置树节点字体样式
     */
     function setFontCss_ztree(treeId, treeNode) {
         /* if (treeNode.id == 0) {
             //根节点
             return {color:"#333", "font-weight":"bold"};
         } else if (treeNode.isParent == false){
             //叶子节点
             return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#660099", "font-weight":"normal"};
         } else {
             //父节点
             return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
         } */
     }
 
 
		
		//==========================搜索树end===================================//
		
		//==========================删除树begin===================================//
		
		function beforeDrag(treeId, treeNodes) {
			return false;
		}

		function remove(e) {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
			nodes = zTree.getSelectedNodes(),
			treeNode = nodes[0];
			if (nodes.length == 0) {
				layer.msg('请先选择一个节点!', {icon: 5});
				return;
			}
			var callbackFlag = $("#callbackTrigger").attr("checked");
			/* zTree.removeNode(treeNode, callbackFlag); */
			
			var confirmVal = false; 
			//询问框
			layer.confirm('确认删除分类[ ' + treeNode.name + ' ]吗？', {
			    btn: ['确定','取消'] //按钮
			}, function(index){
				layer.close(index);
				var data = {id:treeNode.id};
				layer.load(1);
                $.ajax({  
                     async: false,  
                     type: "get",  
                     data:data,
                     url: ctx + "/goodsCategory/delGoodsCategory ",
                     dataType:'json',
                     success: function(data){
                    	 layer.closeAll('loading');
                         if(data.success){  
                        	layer.msg('删除成功!');
                            setTimeout('loadContent("/goodsCategory/categoryList");',500);
                          } else{  
                        	layer.msg(data.msg, {icon: 5});
                          }  
                     },  
                     error: function(){  
                    	 layer.closeAll('loading');
                    	 layer.msg('删除失败!', {icon: 5});  
                     }  
                });  
			});
			
            return confirmVal; 
		};

		
		//==========================删除树end===================================//
		
		//==========================编辑树end===================================//
		
			    //===================编辑校验============================//

		var msg;
		var url;
		function editCategory() {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
			nodes = zTree.getSelectedNodes();
			if (nodes.length == 0) {
				layer.msg('请先选择一个节点!', {icon: 5});
				return;
			}else{
				
				//选取当前选中节点
				treeNode = nodes[0];
				msg = "编辑商品分类";
				url =  ctx + "/goodsCategory/categoryEdit?id="+treeNode.id;
				saveOrUpdateCategoryBox(msg,url);
				
			}
		};

		//==========================编辑树end===================================//
		
		//==========================新增树end===================================//
		
			 
		var id;	
		var msg;
		var url;
		//弹出新增或编辑页面
		function saveOrUpdateCategory () {
			msg = "新增商品分类";
			url = ctx + "/goodsCategory/categoryEdit?id=0";
			saveOrUpdateCategoryBox(msg,url);
		}
		
		var index;
		function saveOrUpdateCategoryBox(msg,url){
		    //官网欢迎页
		     index = layer.open({
		        type: 2,
		        //skin: 'layui-layer-lan',
		        title: msg,
		        fix: false,
		        shadeClose: true,
		        scrollbar: false,
		        maxmin: false,
		        edit: true,
		        closeBtn: 1,
		        area: ['500px', '354px'],
		        content: url,
		        btn: ['确定', '取消']
			    ,yes: function(index, layero){ //或者使用btn1
			        //按钮【按钮一】的回调
			    	var iframeWin = window[layero.find('iframe')[0]['name']]; 
			    	iframeWin.saveOrUpdateCategory();
		
		
			    },cancel: function(index){ //或者使用btn2
			        //按钮【按钮二】的回调
			    }
			    });
		}
		
		//==========================新增树end===================================//
		
		/*保持单一展开路径  */
		var curExpandNode = null;
		function beforeExpand(treeId, treeNode) {
			var pNode = curExpandNode ? curExpandNode.getParentNode():null;
			var treeNodeP = treeNode.parentTId ? treeNode.getParentNode():null;
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			for(var i=0, l=!treeNodeP ? 0:treeNodeP.children.length; i<l; i++ ) {
				if (treeNode !== treeNodeP.children[i]) {
					zTree.expandNode(treeNodeP.children[i], false);
				}
			}
			while (pNode) {
				if (pNode === treeNode) {
					break;
				}
				pNode = pNode.getParentNode();
			}
			if (!pNode) {
				singlePath(treeNode);
			}

		}
		function singlePath(newNode) {
			if (newNode === curExpandNode) return;

            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                    rootNodes, tmpRoot, tmpTId, i, j, n;

            if (!curExpandNode) {
                tmpRoot = newNode;
                while (tmpRoot) {
                    tmpTId = tmpRoot.tId;
                    tmpRoot = tmpRoot.getParentNode();
                }
                rootNodes = zTree.getNodes();
                for (i=0, j=rootNodes.length; i<j; i++) {
                    n = rootNodes[i];
                    if (n.tId != tmpTId) {
                        zTree.expandNode(n, false);
                    }
                }
            } else if (curExpandNode && curExpandNode.open) {
				if (newNode.parentTId === curExpandNode.parentTId) {
					zTree.expandNode(curExpandNode, false);
				} else {
					var newParents = [];
					while (newNode) {
						newNode = newNode.getParentNode();
						if (newNode === curExpandNode) {
							newParents = null;
							break;
						} else if (newNode) {
							newParents.push(newNode);
						}
					}
					if (newParents!=null) {
						var oldNode = curExpandNode;
						var oldParents = [];
						while (oldNode) {
							oldNode = oldNode.getParentNode();
							if (oldNode) {
								oldParents.push(oldNode);
							}
						}
						if (newParents.length>0) {
							zTree.expandNode(oldParents[Math.abs(oldParents.length-newParents.length)-1], false);
						} else {
							zTree.expandNode(oldParents[oldParents.length-1], false);
						}
					}
				}
			}
			curExpandNode = newNode;
		}

		function onExpand(event, treeId, treeNode) {
			curExpandNode = treeNode;
		}
		
	</script>  
	<!-- 解决ie 6 7 8 9不能显示placeholder的问题 -->
	<script src="${ctx}/js/lib/jquery.JPlaceholder.js"></script>
